
package kaizone.haining.chaobohui.fragment;

import java.util.ArrayList;
import java.util.List;

import kaizone.haining.chaobohui.R;
import kaizone.haining.chaobohui.activity.CopyrightActivity;
import kaizone.haining.chaobohui.activity.DetailActivity;
import kaizone.haining.chaobohui.json.Data;
import kaizone.haining.chaobohui.json.JSONResponse;
import kaizone.haining.chaobohui.json.UserCommentDO;
import kaizone.haining.chaobohui.json.UserCommentItem;
import kaizone.haining.chaobohui.login.CommentControl;
import kaizone.haining.chaobohui.login.UserControl;
import kaizone.haining.chaobohui.net.DataControl;
import kaizone.haining.chaobohui.widget.UsersComment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class DetailCommentFragment extends Fragment implements DataControl.IDataUpdateListener {

    public final static String FLAG_TYPE = "type_falg";

    public final static String FLAG_COMMENT_ID = "comment_id_flag";

    public final static String SUBMIT_TYPE_REPLY = "回复";

    public final static String SUBMIT_TYPE_COMMENT = "评论";

    private ListView mListView;

    private EditText mEditText;

    private ImageButton mSubmitView;

    private MyAdapter mAdapter;

    private List<Object> mData;

    private DataControl mDataControl;

    private UserControl mUserControl;

    private CommentControl mCommentControl;

    private Button mCommentBtn;

    private int mType;

    private String mSubmitType;

    private int mId;

    private InputMethodManager mImm;

    private Object mTempObj;

    private String mTargetName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mType = getArguments() != null ? getArguments().getInt(FLAG_TYPE) : 0;
        mId = getArguments() != null ? getArguments().getInt(FLAG_COMMENT_ID) : 0;
        initControl();
    }

    private void initControl() {
        mDataControl = new DataControl(getActivity());
        mDataControl.addChangeListener(this);
        mUserControl = new UserControl(getActivity());
        mCommentControl = new CommentControl();

        mData = new ArrayList<Object>();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = (View) inflater.inflate(R.layout.detail_comment, null);
        mListView = (ListView) view.findViewById(R.id.listview);
        mAdapter = new MyAdapter();
        mListView.setAdapter(mAdapter);
        mListView.setCacheColorHint(0);

        mEditText = (EditText) view.findViewById(R.id.edittext);
        mSubmitView = (ImageButton) view.findViewById(R.id.btn);
        mSubmitView.setImageResource(R.drawable.img_bluebtn_pl);
        mSubmitType = SUBMIT_TYPE_COMMENT;
        mSubmitView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                final String pass = mEditText.getText().toString();
                if (CopyrightActivity.verify(pass)) {
                    CopyrightActivity.come(getActivity());
                    return;
                }
                submitComment();
            }
        });

        mImm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

        initContent();
        return view;
    }

    private void initContent() {
        String url = null;
        if (mType == DetailActivity.FLAG_NEWS) {
            url = mCommentControl.requestQueryNews(mId);
        } else if (mType == DetailActivity.FLAG_HUODONG) {
            url = mCommentControl.requestQueryActivity(mId);
        }
        mDataControl.exec(url);
    }

    @Override
    public Object backParse(String datastring, String requeststring) {
        if (TextUtils.isEmpty(datastring)) {
            return null;
        }
        if (TextUtils.isEmpty(requeststring)) {
            return null;
        }
        //
        if (requeststring.equals(mCommentControl.requestQueryNews(mId))) {
            UserCommentDO userCommentDO = UserCommentDO.parseJson(datastring);
            return userCommentDO;
        }//
        else if (requeststring.equals(requestCommentNews())) {
            JSONResponse response = JSONResponse.parseJsonString(datastring);
            return response;

        }//
        else if (requeststring.equals(requestReplyNews())) {
            JSONResponse response = JSONResponse.parseJsonString(datastring);
            return response;
        }//
        else if (requeststring.equals(mCommentControl.requestQueryActivity(mId))) {
            UserCommentDO userCommentDO = UserCommentDO.parseJson(datastring);
            return userCommentDO;
        }//
        else if (requeststring.equals(requestCommentAct())) {
            JSONResponse response = JSONResponse.parseJsonString(datastring);
            return response;

        }//
        else if (requeststring.equals(requestReplyAct())) {
            JSONResponse response = JSONResponse.parseJsonString(datastring);
            return response;
        }
        return null;
    }

    @Override
    public void foreUpdate(Object result, String requeststring) {
        if (result == null) {
            clearTempData();
            clear();
            return;
        }
        if (TextUtils.isEmpty(requeststring)) {
            clearTempData();
            clear();
            return;
        }
        if (requeststring.equals(mCommentControl.requestQueryNews(mId))
                || requeststring.equals(mCommentControl.requestQueryActivity(mId))) {
            UserCommentDO userCommentDO = (UserCommentDO) result;
            Data data = userCommentDO.getData();
            if (data == null)
                return;
            List<UserCommentItem> items = (List<UserCommentItem>) data.getItems();
            mData.removeAll(mData);
            mData.addAll(items);
            mAdapter.notifyDataSetChanged();
        }//
        else if (requeststring.equals(requestCommentNews())
                || requeststring.equals(requestCommentAct())) {
            if (result instanceof JSONResponse) {
                JSONResponse response = (JSONResponse) result;
                if (response.success) {
                    Toast.makeText(getActivity(), "评论成功", 800).show();
                    initContent();
                } else {
                    Toast.makeText(getActivity(), "评论失败", 800).show();
                }
            }
        }//
        else if (requeststring.equals(requestReplyNews())
                || requeststring.equals(requestReplyAct())) {
            if (result instanceof JSONResponse) {
                JSONResponse response = (JSONResponse) result;
                if (response.success) {
                    Toast.makeText(getActivity(), "回复成功", 800).show();
                    initContent();
                } else {
                    Toast.makeText(getActivity(), "回复失败", 800).show();
                }
            }
        }

        clearTempData();
        clear();
    }

    @Override
    public void exception(Exception e) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getActivity(), "链接异常", 300).show();
                    clear();
                    clearTempData();
                }
            });
        }
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mData != null ? mData.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return mData != null ? mData.get(position) : 0;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            UsersComment userscomment = null;
            if (convertView == null) {
                convertView = (UsersComment) View.inflate(getActivity(), R.layout.item_comment,
                        null);
            }
            userscomment = (UsersComment) convertView;
            final int count = mData.size();
            if (position < count) {
                Object data = mData.get(position);
                if (data instanceof UserCommentItem) {
                    final UserCommentItem usercommentitem = (UserCommentItem) data;
                    userscomment.setContent(usercommentitem.getComment(getActivity()));
                    userscomment.setReply(usercommentitem.ableReply(getActivity()));
                    userscomment
                            .setOnCommentClickListener(new UsersComment.OnCommentClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mTempObj = usercommentitem;
                                    mSubmitView.setImageResource(R.drawable.img_bluebtn_hf);
                                    mSubmitType = SUBMIT_TYPE_REPLY;
                                    mImm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                                    mEditText.requestFocus();
                                }
                            });
                }
            }
            if (position == mData.size()) {
                return mCommentBtn;
            }
            return userscomment;
        }
    }

    public void submitComment() {
        String url = null;
        if (mType == DetailActivity.FLAG_NEWS) {
            url = submitCommentNews();
        } else if (mType == DetailActivity.FLAG_HUODONG) {
            url = submitCommentAct();
        }
        if (TextUtils.isEmpty(url))
            return;
        mDataControl.exec(url);
    }

    public String submitCommentNews() {
        // final String flagText = mSubmitView.getText().toString();
        if (mSubmitType.equals(SUBMIT_TYPE_COMMENT)) {
            return requestCommentNews();
        } else if (mSubmitType.equals(SUBMIT_TYPE_REPLY)) {
            return requestReplyNews();
        }
        return null;
    }

    public String requestCommentNews() {
        final String content = mEditText.getText().toString();
        String url = mUserControl.requestAddCommenNews(mId, content);
        return url;
    }

    public String requestReplyNews() {
        if (mTempObj == null)
            return null;
        if (!(mTempObj instanceof UserCommentItem))
            return null;
        final int toCommentId = ((UserCommentItem) mTempObj).getId();
        final String content = mEditText.getText().toString();
        String url = mUserControl.requestAddReplyNews(mId, toCommentId, content);
        return url;
    }

    public String submitCommentAct() {
        // final String flagText = mSubmitView.getText().toString();
        if (mSubmitType.equals(SUBMIT_TYPE_COMMENT)) {
            return requestCommentAct();
        } else if (mSubmitType.equals(SUBMIT_TYPE_REPLY)) {
            return requestReplyAct();
        }
        return null;
    }

    public String requestCommentAct() {
        final String content = mEditText.getText().toString();
        String url = mUserControl.requestAddCommentActivity(mId, content);
        return url;
    }

    public String requestReplyAct() {
        if (mTempObj == null)
            return null;
        if (!(mTempObj instanceof UserCommentItem))
            return null;
        final int toCommentId = ((UserCommentItem) mTempObj).getId();
        final String content = mEditText.getText().toString();
        String url = mUserControl.requestAddReplyActivity(mId, toCommentId, content);
        return url;
    }

    public void clearTempData() {
        mTempObj = null;
    }

    public void clear() {
        // mSubmitView.setText(SUBMIT_TYPE_COMMENT);
        mSubmitType = SUBMIT_TYPE_COMMENT;
        mSubmitView.setImageResource(R.drawable.img_bluebtn_pl);
        mEditText.setText("");
    }

    public static DetailCommentFragment newInstance(int type, int commentid) {
        final DetailCommentFragment f = new DetailCommentFragment();

        final Bundle args = new Bundle();
        args.putInt(FLAG_TYPE, type);
        args.putInt(FLAG_COMMENT_ID, commentid);
        f.setArguments(args);

        return f;
    }

}
